<template>
  <div class="install-content">
    <div class="content-header">
      <h2>系统安装</h2>
    </div>

    <div class="install-steps">
      <el-steps :active="currentStep" finish-status="success" direction="vertical">
        <el-step v-for="(step, index) in installStore.steps" :key="step.key" :title="step.name"
          :status="getStepStatus(index)">
        </el-step>
      </el-steps>
    </div>

    <div class="install-log">
      <div class="log-header">
        <h3>安装日志</h3>
      </div>
      <div class="log-content" ref="logContent">
        <div v-for="(log, index) in installLogs" :key="index" class="log-item">
          {{ log }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { installStep } from '@/api/install.js'
import { useInstallStore } from '@/stores/install.js'
import { ref, onMounted, nextTick } from 'vue'

const router = useRouter()
const currentStep = ref(0)
const logContent = ref(null)
const installLogs = ref([])
const installStore = useInstallStore()

const addLog = (message) => {
  installLogs.value.push(message)
  nextTick(() => {
    if (logContent.value) {
      logContent.value.scrollTop = logContent.value.scrollHeight
    }
  })
}

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

const getStepStatus = (index) => {
  if (index < currentStep.value) return 'success'
  if (index === currentStep.value) return 'process'
  return 'wait'
}

const startInstall = async () => {
  try {
    for (const step of installStore.steps) {
      addLog(`开始执行: ${step.name}`)
      await installStep(step.key)
      addLog(`${step.name} - 完成安装`)
      currentStep.value++
      await sleep(500)
    }

    ElMessage.success('系统安装完成！')
    router.push('/complete')
  } catch (error) {
    ElMessage.error('安装过程中出现错误：' + error.message)
    addLog(`错误: ${error.message}`)
  }
}

onMounted(() => {
  startInstall()
})
</script>

<style scoped>
.install-content {
  background: #fff;
  border-radius: 4px;
}

.content-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #dcdfe6;
}

.install-steps {
  margin-bottom: 20px;
}

.install-log {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-content {
  height: 300px;
  overflow-y: auto;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.log-item {
  margin-bottom: 5px;
  font-family: monospace;
  white-space: pre-wrap;
}
</style>